package com.jf.car.service.impl;

import com.jf.car.bean.Car;
import com.jf.car.bean.CarImage;
import com.jf.car.dao.CarDao;
import com.jf.car.dao.CarImageDao;
import com.jf.car.dao.impl.CarDaoImpl;
import com.jf.car.dao.impl.CarImageDaoImpl;
import com.jf.car.service.CarService;
import com.jf.car.util.MyUtils;
import com.jf.car.util.PageInfo;
import com.jf.car.util.ResultJson;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CarServiceImpl implements CarService {

    private CarDao carDao = new CarDaoImpl();
    private CarImageDao carImageDao = new CarImageDaoImpl();

    @Override
    public ResultJson getPage(PageInfo pageInfo, Car car) {
        List<Car> list = carDao.getPage(pageInfo,car);
        int count = carDao.getCount(car);
        pageInfo.setPageData(list,count);
        return ResultJson.success(pageInfo);
    }

    @Override
    public ResultJson info(int id) {
        Car car = carDao.getById(id);
        List<CarImage> imgList = carImageDao.getListByCarId(id);
        car.setCarImageList(imgList);
        return ResultJson.success(car);
    }

    @Override
    public ResultJson saveOrUpdate(Car car) {
        int result;
        if(car.getId() == null){
            Car searchInfo = carDao.getByCarNo(car.getCarNo());
            if(searchInfo == null){
                result = carDao.addSelect(car);
            }else{
                return ResultJson.error("车牌号已存在！");
            }
        }else{
            result = carDao.updateSelect(car);
            carImageDao.deleteByCarId(car.getId());
        }
        if(car.getImgs() != null && car.getImgs().length >0){
            List<CarImage> list = new ArrayList<>();
            for(String img:car.getImgs()){
                CarImage ci = new CarImage();
                ci.setId(car.getId());
                ci.setCarImage(img);
                list.add(ci);
            }
            carImageDao.batchImage(list);
        }
        return result > 0?ResultJson.success():ResultJson.error("操作失败！");
    }

    @Override
    public ResultJson delete(int id) {
        int result = carDao.delete(id);
        return result > 0 ? ResultJson.success():ResultJson.error("删除异常！");
    }

    @Override
    public ResultJson getList() {
        List<Car> list = carDao.getList();
        for(Car car: list){
            car.setCarImageList(carImageDao.getListByCarId(car.getId()));
        }
        return ResultJson.success(list);
    }

    @Override
    public Car getById(int id) {
        return carDao.getById(id);
    }
}
